import http from '../utils/http.js'

const API_PATHS = {
  GET_QUESTION_DETAIL: '/jsonrest/mobile/question/QuestionDetail/0/getQuestionDetail',
  GET_ANSWER_ANALYSIS: '/jsonrest/mobile/question/AnswerAnalysis/0/getAnswerAnalysis',
  GET_MICRO_COURSE: '/jsonrest/mobile/course/MicroCourse/0/getMicroCourse'
}

const CHECK_ANSWER_STORAGE_KEY = 'checkAnswer:questionData'

/**
 * 获取题目详情
 * @param {Object} params - 请求参数
 * @param {string} params.questionId - 题目ID
 * @param {string} params.examId - 考试ID
 * @param {string} params.scoreId - 成绩ID
 * @returns {Promise} 题目详情数据
 */
export const getQuestionDetail = ({ questionId, examId, scoreId }) => {
  if (!questionId) throw new Error('[getQuestionDetail] questionId不能为空')
  if (!examId) throw new Error('[getQuestionDetail] examId不能为空')
  if (!scoreId) throw new Error('[getQuestionDetail] scoreId不能为空')

  return http.get(API_PATHS.GET_QUESTION_DETAIL, {
    questionId,
    examId,
    scoreId
  })
}

/**
 * 获取答案解析
 * @param {Object} params - 请求参数
 * @param {string} params.questionId - 题目ID
 * @returns {Promise} 答案解析数据
 */
export const getAnswerAnalysis = ({ questionId }) => {
  if (!questionId) throw new Error('[getAnswerAnalysis] questionId不能为空')

  return http.get(API_PATHS.GET_ANSWER_ANALYSIS, {
    questionId
  })
}

/**
 * 获取微课视频
 * @param {Object} params - 请求参数
 * @param {string} params.questionId - 题目ID
 * @returns {Promise} 微课视频数据
 */
export const getMicroCourse = ({ questionId }) => {
  if (!questionId) throw new Error('[getMicroCourse] questionId不能为空')

  return http.get(API_PATHS.GET_MICRO_COURSE, {
    questionId
  })
}

/**
 * 映射题目详情数据
 * @param {Object} response - API响应数据
 * @returns {Object} 格式化后的题目数据
 */
export const mapQuestionDetail = (response = {}) => {
  const entity = response?.entity || {}
  
  return {
    id: entity.id || entity.questionId,
    title: entity.title || entity.questionTitle || '',
    content: entity.content || entity.questionContent || '',
    options: Array.isArray(entity.options) 
      ? entity.options.map((option, index) => ({
          label: option.label || String.fromCharCode(65 + index), // A, B, C, D
          text: option.text || option.content || ''
        }))
      : [],
    source: entity.source || entity.paperSource || '',
    difficulty: Number(entity.difficulty) || 1,
    type: entity.type || entity.questionType || 'choice',
    answer: entity.answer || entity.correctAnswer || '',
    myAnswer: entity.myAnswer || entity.studentAnswer || '',
    score: Number(entity.score) || 0,
    totalScore: Number(entity.totalScore) || Number(entity.fullScore) || 0,
    status: entity.status || 'unknown' // correct, wrong, partial, unknown
  }
}

/**
 * 映射答案解析数据
 * @param {Object} response - API响应数据
 * @returns {Object} 格式化后的解析数据
 */
export const mapAnswerAnalysis = (response = {}) => {
  const entity = response?.entity || {}
  
  return {
    analysis: entity.analysis || entity.explanation || '',
    images: Array.isArray(entity.images) ? entity.images : [],
    steps: Array.isArray(entity.steps) ? entity.steps : []
  }
}

/**
 * 映射微课数据
 * @param {Object} response - API响应数据
 * @returns {Object} 格式化后的微课数据
 */
export const mapMicroCourse = (response = {}) => {
  const entity = response?.entity || {}
  
  return {
    videoUrl: entity.videoUrl || entity.url || '',
    title: entity.title || entity.courseName || '',
    duration: entity.duration || 0,
    thumbnail: entity.thumbnail || entity.cover || ''
  }
}

/**
 * 预取题目完整数据
 * @param {Object} params - 请求参数
 * @returns {Promise} 完整的题目数据
 */
export const prefetchQuestionData = async ({ questionId, examId, scoreId }) => {
  if (!questionId) throw new Error('[prefetchQuestionData] questionId不能为空')
  if (!examId) throw new Error('[prefetchQuestionData] examId不能为空')
  if (!scoreId) throw new Error('[prefetchQuestionData] scoreId不能为空')

  const [questionRes, analysisRes, microCourseRes] = await Promise.all([
    getQuestionDetail({ questionId, examId, scoreId }),
    getAnswerAnalysis({ questionId }).catch(() => null), // 答案解析可能不存在
    getMicroCourse({ questionId }).catch(() => null) // 微课可能不存在
  ])

  console.log('题目详情:', questionRes)
  console.log('答案解析:', analysisRes)
  console.log('微课视频:', microCourseRes)

  const payload = {
    questionId,
    examId,
    scoreId,
    questionRes,
    analysisRes,
    microCourseRes,
    timestamp: Date.now()
  }

  // 缓存数据
  uni.setStorageSync(CHECK_ANSWER_STORAGE_KEY, payload)
  
  return payload
}

/**
 * 恢复缓存的题目数据
 * @returns {Object|null} 缓存的题目数据
 */
export const restoreQuestionData = () => {
  return uni.getStorageSync(CHECK_ANSWER_STORAGE_KEY) || null
}

/**
 * 清除缓存的题目数据
 */
export const clearQuestionData = () => {
  uni.removeStorageSync(CHECK_ANSWER_STORAGE_KEY)
}

/**
 * 构建页面视图数据
 * @param {Object} payload - 预取的数据
 * @returns {Object} 页面所需的视图数据
 */
export const buildCheckAnswerViewData = (payload) => {
  if (!payload) return null

  const questionDetail = mapQuestionDetail(payload.questionRes)
  const answerAnalysis = payload.analysisRes ? mapAnswerAnalysis(payload.analysisRes) : null
  const microCourse = payload.microCourseRes ? mapMicroCourse(payload.microCourseRes) : null

  return {
    questionInfo: questionDetail,
    answerAnalysis,
    microCourse,
    hasAnalysis: !!answerAnalysis,
    hasMicroCourse: !!microCourse
  }
}

/**
 * 获取题目状态图标
 * @param {string} status - 题目状态
 * @returns {string} 图标路径
 */
export const getStatusIcon = (status) => {
  const iconMap = {
    correct: '/static/icon-correct.png',
    wrong: '/static/icon-wrong.png',
    partial: '/static/icon-partial.png'
  }
  return iconMap[status] || '/static/icon-answer.png'
}

/**
 * 获取难度星级数组
 * @param {number} difficulty - 难度等级 (1-5)
 * @returns {Array} 星级数组
 */
export const getDifficultyStars = (difficulty = 1) => {
  const stars = []
  for (let i = 1; i <= 5; i++) {
    stars.push({
      filled: i <= difficulty,
      icon: i <= difficulty ? '/static/star-filled.png' : '/static/star-empty.png'
    })
  }
  return stars
}

export const useCheckAnswerApi = () => ({
  getQuestionDetail,
  getAnswerAnalysis,
  getMicroCourse,
  mapQuestionDetail,
  mapAnswerAnalysis,
  mapMicroCourse,
  prefetchQuestionData,
  restoreQuestionData,
  clearQuestionData,
  buildCheckAnswerViewData,
  getStatusIcon,
  getDifficultyStars
})

export default {
  getQuestionDetail,
  getAnswerAnalysis,
  getMicroCourse,
  mapQuestionDetail,
  mapAnswerAnalysis,
  mapMicroCourse,
  prefetchQuestionData,
  restoreQuestionData,
  clearQuestionData,
  buildCheckAnswerViewData,
  getStatusIcon,
  getDifficultyStars,
  useCheckAnswerApi
}
